<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary"
               @click=" dialogVisible=true">
      上传图片
    </el-button>
    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :action="uploadAction"
        :headers="headers"
        class="editor-slide-upload"
        list-type="picture-card"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-button @click="dialogVisible = false" controls-position="left">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit" controls-position="left">
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
  // import { getToken } from 'api/qiniu'
  import {getToken} from '@/utils/auth'

  export default {
    components: {
      getToken
    },
    name: 'EditorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff'
      }
    },
    data () {
      return {
        dialogVisible: false,
        listObj: {},
        fileList: [],
        uploadAction: window.SITE_CONFIG.baseUrl + '/sys/oss/upload',
        num: 0,
        successNum: 0
      }
    },
    computed: {
      headers: function () {
        let headers = {'token': getToken()}
        return headers
      }
    },
    methods: {
      checkAllSuccess () {
        return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
      },
      handleSubmit () {
        const arr = Object.keys(this.listObj).map(v => this.listObj[v])
        if (!this.checkAllSuccess()) {
          this.$message('请等待图片上传完成, 如果存在网络问题, 请刷新页面并重新上传!')
          return
        }
        this.$emit('successCBK', arr)
        this.listObj = {}
        this.fileList = []
        this.dialogVisible = false
      },
      handleSuccess (response, file) {
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = file.url
            this.listObj[objKeyArr[i]].hasSuccess = true
            return
          }
        }
      },
      handleRemove (file) {
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            delete this.listObj[objKeyArr[i]]
            return
          }
        }
      },
      beforeUpload (file) {
        if (!this.checkImage(file)) {
          return
        }
        const _self = this
        const _URL = window.URL || window.webkitURL
        const fileName = file.uid
        this.listObj[fileName] = {}
        return new Promise((resolve, reject) => {
          const img = new Image()
          img.src = _URL.createObjectURL(file)
          img.onload = function () {
            _self.listObj[fileName] = {hasSuccess: false, uid: file.uid, width: this.width, height: this.height}
          }
          resolve(true)
        })
      },
      checkImage (file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isPG = (isJPG || isPNG)                                       // 限制图片格式为jpg / png
        const isLt2M = file.size / 1024 / 1024 < 2                         // 限制图片大小
        const isSize = new Promise(function (resolve, reject) {
          let width = 600
          let height = 400
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = img.width >= width && img.height >= height
            // eslint-disable-next-line prefer-promise-reject-errors
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(() => {
          return file
        }, () => {
          this.$message.error('上传图片像素要大于600*400!')
          // eslint-disable-next-line no-undef
          return promise.reject()
        })
        if (!isPG) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isPG && isLt2M && isSize
      }
    }
  }
</script>

<style lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
  }
</style>
